package org.example.controller;

import org.example.entity.ProductEntity;
import org.example.exception.UserException;
import org.example.service.IProductService;
import org.example.util.PageRecord;
import org.example.util.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hanjiafeng
 * @date 2021/4/20 10:11
 * @desc todo
 */
@Controller
@RequestMapping("product")
public class ProductController {

    private final IProductService productService;

    public ProductController(IProductService productService) {
        this.productService = productService;
    }

    @GetMapping("listAllByCid")
    @ResponseBody
    public ResponseEntity<PageRecord<List<ProductEntity>>> listAllByCid(Integer cid, Integer currentPage, Integer pageSize) {

        ResponseEntity<PageRecord<List<ProductEntity>>> responseEntity;
        try {
            PageRecord<List<ProductEntity>> pageRecord = productService.listAllByCid(cid, currentPage, pageSize);
            responseEntity = ResponseEntity.success("查询商品成功");
            responseEntity.setData(pageRecord);
        } catch (UserException e) {
            e.printStackTrace();
            responseEntity = ResponseEntity.failure("查询商品失败");
        }
        return responseEntity;
    }

    @PostMapping("getById")
    @ResponseBody
    public ResponseEntity<ProductEntity> getById(@RequestBody Integer id) {
        ResponseEntity<ProductEntity> responseEntity;
        try {
            ProductEntity productEntity = productService.getById(id);
            responseEntity = ResponseEntity.success("查询商品成功");
            responseEntity.setData(productEntity);
        } catch (UserException e) {
            e.printStackTrace();
            responseEntity = ResponseEntity.failure("查询商品失败:" + e.getMessage());
        }
        return responseEntity;
    }
}
